package com.itheima.blog.admin.aspect;

import com.itheima.api.client.UserClient;
import com.itheima.api.client.dto.WebUser;
import com.itheima.blog.admin.anno.LogListener;
import com.itheima.blog.admin.domain.po.OperationLogTable;
import com.itheima.blog.admin.service.IOperationLogTableService;
import com.itheima.blog.util.UserThreadLocalUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;

@Component
@Aspect
@RequiredArgsConstructor
@Slf4j
public class LogAspect {
    private final UserClient userClient;
    private final RestTemplate restTemplate;
    private final IOperationLogTableService logService;

    @Pointcut("@annotation(com.itheima.blog.admin.anno.LogListener)")
    public void pointcut() {
    }

    @Around("pointcut()")
    @Transactional
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        OperationLogTable logTable = new OperationLogTable();
        //保存日志数据
        //封装用户姓名
        Integer userId = UserThreadLocalUtils.getAdminUserId();
        if (userId!=null){
            WebUser user = userClient.queryWebUserById(Long.valueOf(userId));
            logTable.setUserName(user.getNickname());
        }
        //获取请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //请求路径
        String uri = request.getRequestURI();
        logTable.setAccessInterface(uri);
        log.info("开始记录操作日志,uri:{}",uri);
        //ip
        String ip = request.getRemoteAddr();
        logTable.setIp(ip);
        //查询ip地址
        String url = "https://api.map.baidu.com/location/ip?ak=MkeRswSQ2OjIFG1XDtMRljdQNFo3mxT6AK&ip="+ip;
        String addressObj = restTemplate.getForObject(url, String.class);

        String[] split = addressObj.split("\"");
        if (split.length>2){
            String s = split[1];
            String[] split1 = s.split("\\|");
            if (split1.length>1){
                String country = split1[0];
                String s1 = split1[1];
                logTable.setKingdom(country);
                logTable.setEconomize(s1);
            }

        }

        //处理请求耗时
        LocalDateTime startTime = LocalDateTime.now();
        logTable.setCreationTime(startTime);
        logTable.setTime(startTime);

        //处理请求类型
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();

        LogListener annotation = method.getAnnotation(LogListener.class);
            logTable.setInterfaceName(annotation.value());
            logTable.setRequestMethod(annotation.type());

            //放行
        Object proceed = pjp.proceed();

        //获取时间
        LocalDateTime endTime = LocalDateTime.now();
        //请求耗时
        Duration dur= Duration.between(startTime,endTime);
        long time = dur.toMillis();
        logTable.setTimeConsuming(time);
        if (time == 1){
            logTable.setState("正常");
        }else if (time >=1&&time <80){
            logTable.setState("一般");
        } else if (time >=80) {
            logTable.setState("超时");
        }
        //保存到数据库
        logService.save(logTable);

        return proceed;

    }



}
